import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Form, Select, Input, Switch } from 'antd'
import { emailPattern } from '@js/config'
const { Item } = Form
const { Option } = Select
class Detail extends Component {
  state = {
    contractList: [],
    initData: {},
    type: ''
  }

  formRef = React.createRef()

  // 改变主体类型
  changeSubject (e, contractid) {
    const d = this.props.caseDetail
    let list = []
    switch (e) {
      case '申请人':
        list = d.applicants.filter(li => li.status)
        break
      case '被申请人':
        list = d.respondents.filter(li => li.status)
        break
      case '申请人代理人':
        list = d.applicant_agents
        break
      case '被申请人代理人':
        list = d.respondents_agents
        break
      case '仲裁员':
        list = this.props.arbitrators
        break
      default:
        list = []
        break
    }
    this.setState({
      contractList: list,
      type: e
    }, () => {
      this.formRef.current.setFieldsValue({ action_subject: e, contractid })
    })
  }

  // 改变主体
  changeContractId (id) {
    const c = this.formRef.current
    const list = this.state.contractList
    const type = c.getFieldValue('action_subject')
    let obj = null
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === id) {
        obj = list[i]
      }
    }
    const data = {
      contractid: id,
      mobile: obj.mobile,
      address: obj.address,
      type: '',
      tel: obj.tel,
      tel_office: '',
      zip_code: obj.zip_code,
      contract_type: '自然人'
    }
    if (['申请人', '被申请人'].indexOf(type) !== -1) {
      if (['企业', '非法人组织'].indexOf(obj.subject_type) !== -1) {
        data.structure = obj.name
        data.contract = ''
        data.contract_type = obj.subject_type === '企业' ? '法人' : '非法人组织'
      } else {
        data.structure = ''
        data.contract = obj.name
      }
    } else if (type.indexOf('代理人') !== -1) {
      data.structure = ''
      data.contract = obj.name
    } else if (type === '仲裁员') {
      data.contract = obj.name
      data.address = obj.structure_address
      data.tel_office = obj.structure_tel
      data.structure = obj.structure
      data.zip_code = obj.zip
    }
    c.setFieldsValue(data)
  }

  handleOk () {
    this.formRef.current.submit()
  }

  finishHandle (d) {
    this.props.onFinish(d)
  }

  initFormData () {
    const d = this.props.data || { }
    this.changeSubject(d.action_subject)
    d.status = d.status === 1
    this.setState({
      initData: d || {}
    }, () => {
      this.formRef.current.resetFields()
    })
  }

  componentDidUpdate (prev) {
    if (prev.data !== this.props.data) {
      this.initFormData()
    }
  }

  // 渲染送达类型
  renderSendType () {
    const addressTypes = this.props.dictionaries['电子送达地址类型'] || []
    if (this.state.type !== '仲裁员') {
      return (
        <Item name='type' label='地址类型' rules={[{ required: true, message: '地址类型不能为空' }]}>
          <Select placeholder='请选择地址类型'>
            {
              addressTypes.map(li => {
                return <Option key={li.title} value={li.title}>{li.title}</Option>
              })
            }
          </Select>
        </Item>
      )
    }
  }

  render () {
    const initData = this.state.initData || {}
    return (
      <Modal
        title={initData.id ? '修改地址' : '新增地址'}
        open={this.props.visible}
        width={600}
        onOk={() => this.handleOk()}
        onCancel={() => this.props.hide()}
        maskClosable={false}
      >
        <Form name='add-service' labelCol={{ span: 4 }} ref={this.formRef} initialValues={initData} onFinish={d => this.finishHandle(d)}>
          <Item name='action_subject' label='仲裁地位' rules={[{ required: true, message: '仲裁地位不能为空' }]}>
            <Select placeholder='请选择仲裁地位' onChange={e => this.changeSubject(e)}>
              {
                ['申请人', '被申请人', '申请人代理人', '被申请人代理人', '仲裁员'].map(li => {
                  return <Option key={li} value={li}>{li}</Option>
                })
              }
            </Select>
          </Item>
          <Item name='id' noStyle><span /></Item>
          <Item name='address_type' noStyle><span /></Item>
          <Item name='contractid' label='主体' rules={[{ required: true, message: '主体不能为空' }]}>
            <Select placeholder='请选择主体' onChange={e => this.changeContractId(e)}>
              {
                this.state.contractList.map(li => {
                  return <Option key={li.id} value={li.id}>{li.name}</Option>
                })
              }
            </Select>
          </Item>
          {this.renderSendType()}
          <Item name='contract' label='收件人'>
            <Input placeholder='请输入收件人' />
          </Item>
          <Item name='contract_type' noStyle><span /></Item>
          <Item name='structure' label='单位'>
            <Input placeholder='请输入单位' />
          </Item>
          <Item name='mobile' label='手机号码' rules={[{ required: true, message: '手机号码不能为空' }, { pattern: /^1\d{10}(,1\d{10})*$/, message: '手机号码格式不正确，多个号码请以英文逗号隔开' }]}>
            <Input placeholder='请输入手机号码' />
          </Item>
          <Item name='email' label='电子邮箱' rules={[{ pattern: emailPattern, message: '电子邮箱格式不正确，多个电子邮箱请以英文逗号隔开' }]}>
            <Input placeholder='请输入电子邮箱' />
          </Item>
          <Item name='status' label='是否有效' valuePropName='checked'>
            <Switch checkedChildren='有效' unCheckedChildren='无效' />
          </Item>
        </Form>
      </Modal>
    )
  }
}

Detail.propTypes = {
  visible: PropTypes.bool,
  data: PropTypes.object,
  caseDetail: PropTypes.object,
  hide: PropTypes.func,
  onFinish: PropTypes.func,
  dictionaries: PropTypes.object,
  arbitrators: PropTypes.array
}
Detail.defaultProps = {
  visible: false,
  data: {},
  caseDetail: {},
  hide: () => {},
  onFinish: () => {},
  dictionaries: {},
  arbitrators: []
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(Detail)
